<template>
  <div class="system-setting" @click.capture="closeModel">
    <div id="sysSettingForm" class="sysSettingForm">
      <base-form :isAutoUpload="true" :formState="formState" :showRadioPop='showRadioPop' @uploadFinished="uploadFinished"
        @closeContentSecurate="closeContentSecurate" @resetTextarea="resetTextarea"
        @upload_remove_Finished='upload_remove_Finished' @getIndex="getIndex" ref="getbaseForm">
        <template #addDomain="addDomainOptions">
          <div :style="{ marginTop: 0 + 'px' }" class="form-a-radio-group">
            <a-button @click="isShowAddModel = isShowAddModel ? false : true" type="primary" class="add-btn">
              添加元素
              <i class="iconfont icon-down" style="font-size:24px;margin-left: 8px;color:#fff"></i>
              <div class="add-box" v-if="isShowAddModel">
                <div class="single-add">
                  <span class="add-text">单次添加项</span>
                  <div class="list" @click="handleMenuClick(item)" selectable v-for="(item, index) in chooseList">
                    <div class="item" :class="item.selected ? 'item-selected' : ''">
                      {{ item.desc }}
                      <i v-if="item.selected" class="iconfont icon-hook"
                        style="font-size:24px;margin-left: 8px;color:#1f6ded;"></i>
                    </div>
                  </div>
                </div>
                <div class="line"></div>
                <div class="multi-add">
                  <span class="add-text">重复添加项</span>
                  <div class="list" @click="handleMenuClick(divider)">
                    <div class="item">
                      分隔符
                    </div>
                  </div>
                </div>
              </div>
            </a-button>
            <draggable :list="addDomainOptions.list" ghost-class="edit-ghost" handle=".edit" filter=".forbid"
              :force-fallback="true" chosen-class="edit-chosenClass" animation="300" @start="onStart" @end="onEnd"
              :fallback-class="true" dragClass="dragClass" :fallback-on-body="true" :touch-start-threshold="50"
              :fallback-tolerance="50" :move="onMove">
              <template #item="{ element, index }">
                <div class="add-item edit">
                  <i class="iconfont icon-drag" style="line-height: 32px;"></i>
                  <i class="iconfont icon-delete" style="font-size:16px;margin-left: 16px;"
                    @click="deleteDomain(element.type, index)"></i>
                  <div class="element-item">{{ element.desc }}</div>
                  <div v-if="element.code === 'indexNumRuleSeqNumRule'">
                    <a-input-number class="inputNumber" @change="sortNumChange" v-model:value="sortNum" :min="1" :max="10" :precision="0" />
                  </div>
                </div>
              </template>
            </draggable>
          </div>
        </template>
      </base-form>
    </div>
    <div class="table-bottom_fiexd" :style="styleWidth">
      <a-button type="primary" :disabled="!btnPerm.includes('saveAble')" @click="saveButton">保存</a-button>
    </div>
  </div>
</template>
      

<script lang="ts" setup>
import { ref, reactive, watch, onMounted, nextTick } from "vue";
import { dataSourceType, detailDataItemType } from "@/type.d";
import { sysSettingForm } from './formCofig';

import getters from "@/store/getters";
import { useUserStore } from "@/store/modules/user";
import { cloneDeep } from 'lodash'
import baseForm from '@/components/form/baseForm.vue'
import request from "@/api/index"
import draggable from "vuedraggable";
import { message } from "ant-design-vue";
import { SET_SETTING_System_Icon } from '@/utils/common';

import { useFixeWidth, styleWidth } from '@/hooks/useFixeWidth';
import { routerPerm } from '@/utils/common'
// props
const props = defineProps({
  extendInfo: {
    type: Object,
    default: {}
  },
  id: {
    type: Number,
    default: 1
  }
})
//getters || store
const userStore = useUserStore();
const userInfo = getters.userInfo();
// data
const sysSettingInfo = ref<detailDataItemType>([])
const chooseList = ref<(dataSourceType[])>([]);
const originList = ref<(dataSourceType | any[])>([]);
const choosedList = ref<(dataSourceType | any[])>([]);
const formState = ref<(dataSourceType)[]>(cloneDeep(sysSettingForm));
const sectionIndex = ref<(number)>(0);
const showRadioPop = ref<boolean>(false)
const formItemIndex = ref<(number)>(0);
const ftpList = ref<(dataSourceType[])>([]);
const ossList = ref<(dataSourceType[])>([]);
const configId = ref<(number)>(0);
let divider = { code: "indexNumRuleSplitChar", desc: "分隔符", type: 8 };
const getbaseForm = ref();
const isShowAddModel = ref<boolean>(false);
const section_index = ref(0)
const formItem_index = ref(0)
const btnPerm = ref<any[]>([]);
const sortNum = ref<number>(1);
//watch
watch(() => sysSettingInfo.value[0], async (newVal: any, oldVal) => {
  // console.log(newVal, 33333333);

  if (!newVal) {
    formState.value = cloneDeep(sysSettingForm);
    return;
  }
  if (JSON.stringify(newVal)) {
    formState.value.forEach((item) => {
      if (newVal.hasOwnProperty(item.id)) {
        item.children.forEach(async (data: dataSourceType) => {
          if (newVal[item.id]?.hasOwnProperty(data.param)) {
            if (data.value instanceof Array) {
              data.value = [];
              if (data.picIdPram) { // 图片格式
                let obj = {
                  uid: '',
                  url: newVal[item.id][data.param]
                }
                if (obj.url) {
                  data.value.push(obj)
                  data.picId = newVal[item.id][data.picIdPram];
                }

              } else { // 多选格式
                newVal[item.id][data.param] && newVal[item.id][data.param] instanceof Array ?
                  data.value = newVal[item.id][data.param] : data.value.push(newVal[item.id][data.param]);
              }
            } else {
              if (data.param === 'uploadFileLocationValue' || data.param === 'backupFileServerTypeValue' || data.param === 'templateFileServerValue') {
                let OssList = await request.fetchSysConfigOssList({});
                let FtpList = await request.fetchSysConfigFtpList({})
                nextTick(() => {
                  FtpList.forEach((item: any) => {
                    item.value = item.id;
                    item.label = item.name;
                  })
                  OssList.forEach((item: any) => {
                    item.value = item.id;
                    item.label = item.name;
                  })
                  data.options = data.associatedValue === 2 ? FtpList : OssList
                })

              }
              data.value = newVal[item.id][data.param] != null ? newVal[item.id][data.param] : '';
              if(data.param === 'backupFileServerTypeValue') {
                data.value = newVal[item.id][data.param] != null ? +newVal[item.id][data.param] : '';
              }
              if(data.param === 'contributeModelId') {
                let modelList = await request.fetchColumnModelList({modelType: 2, type: 1});
                nextTick(() => {
                  modelList.forEach((item: any) => {
                    item.value = item.id;
                    item.label = item.name;
                  })
                  data.options = modelList;
                })
              }
            }
          }
        })
      }
    });
  }
}, { deep: true })

//methods
const sortNumChange = (val: any) => {
  if(!val) {
    sortNum.value = 1
  }
};

//拖拽开始
const onStart = (e: any) => {
  console.log(e, "开始拖拽");
}
//拖拽结束的事件
const onEnd = (e: any) => {
  // console.log(arr2, 99991)
}
const onMove = (e: any) => {
}


const closeModel = () => {
  isShowAddModel.value = false
}
//点击下拉菜单
const handleMenuClick = (data: dataSourceType) => {
  if (data.type == 8) {
    choosedList.value.push(data)
  } else {
    originList.value.forEach((item: any, index: number) => {
      item.sort = index
      if (data.type == item.type) {
        item.selected = item.selected ? false : true
        item.selected ? choosedList.value.push(item) : choosedList.value = choosedList.value.filter((item: any) => item.type !== data.type)
      }
    })
  }
  sysSettingInfo.value[0].contentSettingsDto.indexNumSetting = choosedList.value

  sysSettingInfo.value[0].contentSettingsDto.contentIssue = true

}

//删除索引号
const deleteDomain = (type: number, index: number) => {
  choosedList.value.splice(index, 1)
  originList.value.forEach((item: any, index: number) => {
    if (type !== 8 && type === item.type) {
      item.selected = false
    }
  })
  sysSettingInfo.value[0].contentSettingsDto.indexNumSetting = choosedList.value
}


//单选框改变事件
const onChange = (e: boolean, name: string) => {

}

// 获取index
const getIndex = (section_index: number, formItem_index: number,) => {
  sectionIndex.value = section_index;
  formItemIndex.value = formItem_index;
}

//关闭内容密集弹窗
const closeContentSecurate = (index1: number, index2: number) => {
  showRadioPop.value = true
  formState.value[2].children[0].value = false
}


watch(() => formState.value[2].children[0].value, (newVal, oldVal) => {
  showRadioPop.value = newVal ? false : true
})

// 上传图片返回值
const uploadFinished = (data: any) => {
  formState.value[sectionIndex.value].children[formItemIndex.value].value.splice(0, 1);
  formState.value[sectionIndex.value].children[formItemIndex.value].value.push(data[0]);
  formState.value[sectionIndex.value].children[formItemIndex.value].picId = data[0].id;
}


// 重置白名单
const resetTextarea = (item: dataSourceType, index1: number, index2: number) => {
  formState.value[index1].children[index2].value = sysSettingInfo.value[0][formState.value[index1].id][item.param]
}

// 删除图片
const upload_remove_Finished = (data: any) => {
  setTimeout(() => {
    formState.value[sectionIndex.value].children[formItemIndex.value].value.splice(0, 1);
    getbaseForm.value.baseForm.validateFields([sectionIndex.value, 'children', formItemIndex.value, 'value']).then((res: any) => {
      console.log(res, 6633)
    })
  }, 10);

}
// 获取已设置的站点最新的基础信息和扩展信息
const setNewValue = () => {
  const accountSafeNewValue: dataSourceType = {}
  accountSafeNewValue.configId = configId.value
  formState.value.forEach((item: dataSourceType) => {
    accountSafeNewValue[item.id] = {};
    item.children.forEach((data: dataSourceType) => {
      if (data.hasOwnProperty('param')) {
        if (data.picIdPram) { // 图片类的
          accountSafeNewValue[item.id][data.param] = data.value[0]?.url || '';
        } else if (data.param === 'indexNumSetting') {
          accountSafeNewValue[item.id][data.param] = choosedList.value
        } else {
          if(data.param == 'backupFileServerTypeValue') {
            if(data.associatedValue == item.children.find((associate:any)=>associate.param=='backupFileServerType').value){
              accountSafeNewValue[item.id][data.param] = +data.value;
             }
          }else {
            accountSafeNewValue[item.id][data.param] = data.value === "" ? null : data.value;
          }
        }
      }
    })
  })
  return accountSafeNewValue
}


//保存数据
const saveButton = async () => {
  const accountSafeNewValue = setNewValue();
  accountSafeNewValue.contentSettingsDto.indexNumSetting = sysSettingInfo.value[0].contentSettingsDto.indexNumSetting
  accountSafeNewValue.contentSettingsDto.indexNumSetting.forEach((item: any, index: number) => {
    item.sort = index
    if(item.code === 'indexNumRuleSeqNumRule') {
      item.val = sortNum.value
    }
  })
  console.log(accountSafeNewValue, 'accountSafeNewValue')
  let accountSafeForm = getbaseForm.value.baseForm;
  accountSafeForm.validate()
    .then(() => {
      request.fetchSysConfigUpdate(accountSafeNewValue).then((res: dataSourceType) => {
        if (res.code === '00000 00000') {
          let obj: any = {
            tabPic: accountSafeNewValue?.otherSettingsDto?.tabPic,
            loginPagePic: accountSafeNewValue?.otherSettingsDto?.loginPagePic,
            sysHeaderLogo: accountSafeNewValue?.otherSettingsDto?.sysHeaderLogo,
            pageTitleSetting: accountSafeNewValue?.otherSettingsDto?.pageTitleSetting,
          };
          userStore.setUser(Object.assign(userInfo, obj));
          message.success(res.message)
          fetchSysConfigDetail();
        } else {
          message.error(res.message)
        }
      })
    }).catch((err: any) => {
      setTimeout(() => {
        let errors = document.querySelector('.ant-form-item-explain-error');
        errors?.scrollIntoView({
          behavior: 'smooth',
          block: 'center'
        })
      }, 100)
    });
}


//获取详情内容
const fetchSysConfigDetail = async () => {
  request.fetchSysConfigDetail({}).then((res: dataSourceType | any) => {
    configId.value = res.configId;
    sysSettingInfo.value.push(res);
    const sortNumVal = sysSettingInfo.value[0].contentSettingsDto.indexNumSetting.find((item:any) => item.code === 'indexNumRuleSeqNumRule')
    if(sortNumVal) {
      sortNum.value = +sortNumVal.val
    }
    fetchSysConfigIndexUnits()
  });
}
//获取索引号列表
const fetchSysConfigIndexUnits = async () => {
  request.fetchSysConfigIndexUnits({}).then((res: dataSourceType | any) => {
    originList.value = res || []
    chooseList.value = originList.value.length && originList.value.filter((item: dataSourceType) => item.type != 8)
    choosedList.value = []
    originList.value.length && originList.value.forEach((item: dataSourceType) => {
      sysSettingInfo.value[0]?.contentSettingsDto?.indexNumSetting.length && sysSettingInfo.value[0]?.contentSettingsDto?.indexNumSetting.forEach((jitem: dataSourceType) => {
        if (item.type === jitem.type && item.type != 8) {
          item.selected = true
          choosedList.value.push(item)
        } else if (item.type === jitem.type && jitem.type === 8) {
          choosedList.value.push(item)
        }
      })
    })
  });
}


//获取ossList列表
const fetchSysConfigOssList = async () => {
  request.fetchSysConfigOssList({}).then((res: dataSourceType | any) => {
    // console.log(res, '321321')
    ossList.value = res
  });
}

//获取ftpList列表
const fetchSysConfigFtpList = async () => {
  request.fetchSysConfigFtpList({}).then((res: dataSourceType | any) => {
    // console.log(res, '5555')
    ftpList.value = res
  });
}

//onMounted
onMounted(() => {
  btnPerm.value = routerPerm();
    fetchSysConfigDetail()
  // fetchSysConfigFtpList()
  // fetchSysConfigOssList()
  useFixeWidth()
})
</script>
<style lang="less" scoped>
.add-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-top: 16px;
  cursor: move;
    .inputNumber {
      margin-left: 8px;
    }
  .icon-delete {
    cursor: pointer;
  }

  .element-item {
    margin-left: 16px;
  }
}

.add-btn {
  position: relative;
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 24px;
}

.add-item:first-child {
  margin-top: 0;
}

.single-add {
  .item {
    height: 38px;
    display: flex;
    flex-direction: row;
    align-items: center;
    color: rgba(0, 0, 0, 0.85);
    justify-content: space-between;
  }

  .item-selected {
    color: #1f6ded;
  }
}

.multi-add {
  .item {
    height: 38px;
    display: flex;
    flex-direction: row;
    align-items: center;
    color: rgba(0, 0, 0, 0.85);
    justify-content: space-between;
  }
}

.line {
  border-bottom: 1px solid #f0f0f0;
  margin: 10px 0;
}

.add-box {
  position: absolute;
  left: 0;
  top: 48px;
  width: 160px;
  background-color: #fff;
  padding: 8px 20px;
  z-index: 1000;
  box-shadow: 0 -3px 16px 0 rgb(89 155 255 / 15%);

}

.add-box::before {
  border: solid transparent;
  content: ' ';
  height: 0;
  left: 30%; //根据三角形的位置，可以随意更改。
  position: absolute;
  width: 0;
  border-width: 5px;
  border-bottom-color: #fff;
  top: -10px;
}

.add-text {
  text-align: left;
  display: block;
  line-height: 1;
  font-size: 12px;
  color: #b2b2b2;
  padding: 12px 0px;
}

.system-setting {
  padding-left: 16px;
  height: 100%;
  background-color: #fff;
  width: 100%;
  height: calc(100% - 136px);
  padding-bottom: 56px;

  .sysSettingForm {
    height: 100%;
    overflow-y: auto;
  }


  .table-bottom_fiexd {
    height: 48px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    bottom: 0;
    z-index: 10;
    background: #fff;
  }
}
</style>
<style lang="less">
#sysSettingForm {

  .ant-form-item-label {
    text-align: right;
    width: 196px;
    margin-right: 8px;
  }
}

.form-a-radio-group {
  // 禁止文字被鼠标选中 
  moz-user-select: -moz-none;
  -moz-user-select: none;
  -o-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
</style>